# -*- coding:UTF-8 -*-
"""
@Project:   DataCrawler
@FileName:  file_method.py 
@Create:    2023/5/1 12:23  
@Author:    Jia  
@Descr:    ->对文件进行增 删 改 写 的操作
"""
import yaml
import os
import shutil

"""
# body = resp.json()
# json.loads():str转dict;
# json.dumps():dict转str;
# json.load(file):将file读取出来
# json.dump(obj,file):将json信息写入文件
"""


class FileMethod:

    @classmethod
    def clean_dir(cls, dir_path):
        """清空存在的目录 重新创建新的"""

        if not os.path.exists(dir_path):
            os.mkdir(dir_path)
        else:
            shutil.rmtree(dir_path)
            os.mkdir(dir_path)

    @classmethod
    def get_project_path(cls, project_name):
        """输入项目名 获取项目根目录"""

        abs_path = os.path.abspath(project_name)
        path1 = abs_path.split(project_name)
        # project_path = ''.join([path1[0], project_name])
        project_path = os.path.join(path1[0], project_name)

        return project_path

    @classmethod
    def write_file(cls, file_path, write_text):
        """向文件写入文本"""

        with open(file_path, 'w', encoding='utf-8') as wf:
            wf.write(write_text)

    @classmethod
    def read_yaml(cls, f_path):
        """读取yaml文件数据"""

        with open(f_path, encoding='utf-8', mode='r') as f:
            ff = yaml.load(f, Loader=yaml.FullLoader)
            return ff

    @classmethod
    def write_yaml(cls, f_path, f_data):
        """向YAML文件写入数据"""

        with open(f_path, encoding='utf-8', mode='w') as wf:
            yaml.dump(f_data, stream=wf)

    @classmethod
    def clear_yaml(cls, f_path):
        """ 将yaml文件内容清除"""

        with open(f_path, encoding='utf-8', mode='r+') as cf:
            cf.truncate()

    @classmethod
    def read_extract_yaml(cls, project_name, one_name):
        """取根目录中extract文件的值"""

        file_path = str(cls.get_project_path(project_name) + r'\extract.yaml.yaml.yml')
        with open(file_path, mode='r', encoding='utf-8') as rf:
            extract = yaml.load(rf.read(), Loader=yaml.FullLoader)
            return extract[one_name]

    @classmethod
    def test_modify(cls, f_path, in_para, one_name, two_name):
        """
        修改YAML文件参数
        :f_path 打开文件的路径
        :in_para 输入的参数
        :one_name 字典第一个key
        :two_name 字典第二个kdy
        """
        with open(f_path) as f:
            doc = yaml.safe_load(f)
            doc[one_name][two_name] = in_para
        with open(f_path, 'w') as wf:
            yaml.safe_dump(doc, wf, allow_unicode=True)


if __name__ == '__main__':
    name = 'DataCrawler'
    FileMethod.get_project_path(name)
